package edu.whu.demo.controller;



import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import edu.whu.demo.domain.Commodity;
import edu.whu.demo.domain.Commodity_suppliers;
import edu.whu.demo.domain.Supplier;
import edu.whu.demo.exception.ProductAdminException;
import edu.whu.demo.service.impl.CommodityServiceImpl;
import edu.whu.demo.service.impl.Commodity_suppliersServiceImpl;
import edu.whu.demo.service.impl.SupplierServiceImpl;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yang hengyi
 * @since 2022-10-24
 */
@RestController
@RequestMapping("/commodity")
public class CommodityController {
    @Autowired
    CommodityServiceImpl commodityService;

    @Autowired
    Commodity_suppliersServiceImpl commoditySuppliersService;

    @Autowired
    SupplierServiceImpl supplierService;

    @ApiOperation("根据id获取商品")
    @GetMapping("/{id}")
    public ResponseEntity<Commodity> getCommodity(@PathVariable long id) {
        Commodity commodity = commodityService.getById(id);
        if(commodity == null) {
            return ResponseEntity.noContent().build();
        }
        else{
            List<Long> ids = commoditySuppliersService.getSupplierByCommodity(commodity.getId());
            commodity.setSuppliers(supplierService.batchGetSuppliers(ids));
            return ResponseEntity.ok(commodity);
        }
    }

    @ApiOperation("添加商品")
    @PostMapping("")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<Commodity> addCommodity(@RequestBody Commodity commodity) throws Exception{
        Commodity result = commodityService.addCommodity(commodity);
        for(Supplier supplier: commodity.getSuppliers()){
            if(supplierService.getById(supplier.getId()) != null) {
                commoditySuppliersService.save(new Commodity_suppliers(result.getId(), supplier.getId()));
            }
        }
        return ResponseEntity.ok(commodity);
    }

    @ApiOperation("根据条件查找商品")
    @GetMapping("")
    public ResponseEntity<Page<Commodity>> findCommodity(@ApiParam("商品名称") String name,
                                                         @ApiParam("商品价格") Double price,
                                                         @ApiParam("商品数量") Integer number,
                                                         @ApiParam("页号") @RequestParam(defaultValue = "0") Integer pageNum,
                                                         @ApiParam("页面大小") @RequestParam(defaultValue = "5") Integer pageSize) {
        Map<String, Object> map = new HashMap<>();
        if(name != null) {
            map.put("name", name);
        }
        if(price != null) {
            map.put("price", price);
        }
        if(number != null) {
            map.put("number", number);
        }

        Page<Commodity> page = commodityService.findCommodity(map, new Page<>(pageNum, pageSize));
        if(page.getRecords().size() > 0) {
            return ResponseEntity.ok(page);
        }
        else{
            return ResponseEntity.noContent().build();
        }
    }

    @PutMapping("")
    @Transactional
    @ApiOperation("修改商品信息")
    public ResponseEntity<Commodity> updateCommodity(@NotNull Commodity commodity) throws Exception{
        Optional.ofNullable(commodityService.getById(commodity.getId()))
                .orElseThrow(()->new ProductAdminException("无该项数据"));

        commodityService.updateCommodity(commodity);
        commoditySuppliersService.batchDeleteByCommodityId(commodity.getId());
        for(Supplier supplier: commodity.getSuppliers()){
            if(supplierService.getById(supplier.getId()) != null) {
                commoditySuppliersService.save(new Commodity_suppliers(commodity.getId(), supplier.getId()));
            }
        }
        return ResponseEntity.ok(commodity);
    }

    @ApiOperation("删除商品")
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteCommodity(@PathVariable Long id) throws Exception{
        commoditySuppliersService.batchDeleteByCommodityId(id);
        commodityService.deleteCommodity(id);
        return ResponseEntity.ok().build();
    }
}

